package com.ffcs.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;

import net.sf.json.JSONObject;

import com.ffcs.constants.FfcsConstants;
import com.smart.util.WeixinUtil;

import open189.sign.ParamsSign;

/**
 * 下发短信验证码DEMO
 *
 */
public class SendRandcode
{
	public static String URL = "http://www.smartcommunitytest.cn/SmartCommunity/wechat/rand_redirect";//验证码通知接口地址---需要保证接口地址在公网能被访问

	public static String getPostEntity(String userPhone) throws UnsupportedEncodingException
	{
		//先获取令牌接口
		String ACCESS_TOKEN=RandomAccessTokenManager.getRandomAccessToken();
		//再获取信任码
		String token=TokenManager.getToken();
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timestamp = dateFormat.format(date);
		TreeMap<String, String> paramsMap = new TreeMap<String, String>();
		paramsMap.put("app_id", FfcsConstants.APPID);
		paramsMap.put("access_token", ACCESS_TOKEN);
		paramsMap.put("timestamp", timestamp);
		paramsMap.put("token", token);
		paramsMap.put("url", URL);		
		paramsMap.put("phone", userPhone);
		paramsMap.put("exp_time", "2");
		String postEntity = "app_id="+FfcsConstants.APPID
								  + "&access_token="+ACCESS_TOKEN
								  + "&token=" +token
						          + "&phone=" + userPhone			          
						          + "&url=" + URL					          
						          + "&exp_time=2"
						          + "&timestamp="+ URLEncoder.encode(timestamp, "UTF-8") 
						          + "&sign="+ParamsSign.value(paramsMap,FfcsConstants.APPSECRET);
		System.out.println(postEntity); 		
		return postEntity;
	}
	/**
	 * 1 获取信任码token get提交
	 * 2自定义短信验证码下发 post提交
	 * @param userPhone 下发手机号
	 * @return
	 * @throws Exception
	 */
	public static String sendSms(String userPhone) throws Exception {
		System.out.println("sendSms method start");
		String postUrl =FfcsConstants.RANDOM_CODE_URL;
		String postEntity=getPostEntity(userPhone);
		//准备循环获取10次，因为经常会获取失败
		String identifier=null;
		for(int i=0;i<10;i++)
		{
		 JSONObject jsonObject = WeixinUtil.doPostStr2(postUrl,postEntity);
		 System.out.println(jsonObject);
		 String res_code=jsonObject.getString("res_code");
		 if(res_code.equals("0")) 
		 {
		        System.out.println("验证码获取成功");identifier=jsonObject.getString("identifier");break;
		  }
		 else 
		  {
			 System.out.println("验证码获取失败");
			 System.out.println("得重新对postEntity进行获取");
			 postEntity=getPostEntity(userPhone);
		  }
		}
		System.out.println("sendSms method finish");
		return identifier;
	}

		public static void main(String[] args) throws Exception {
			
			try {
				 String result=sendSms("");
				 System.out.println(result);
			}finally{

		}

}


}